//
//  ZHAbility.m
//  Base
//
//  Created by zhusanbao on 2021/1/11.
//

#import "ZHAuthority.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@implementation ZHAuthority

+ (void)cameraCheck:(void (^)(ZHAuthorityStatus, NSString * _Nullable))callback{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted){//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        if (callback) callback(ZHAuthorityDeny, @"APP无法访问相机，请检测手机是否开启了家长控制");
    }else if (authStatus ==AVAuthorizationStatusDenied){ //用户已经明确否认了这一照片数据的应用程序访问
        if (callback) callback(ZHAuthorityDeny, @"APP无法访问相机，请到手机'设置'允许APP访问相机权限");
    }else if (authStatus ==AVAuthorizationStatusAuthorized){ //用户已经明确否认了这一照片数据的应用程序访问
        if (callback) callback(ZHAuthorityOK, nil);
    }else{
        if (callback) callback(ZHAuthorityUnkonw, nil);
    }
}

+ (void)photoCheck:(void (^)(ZHAuthorityStatus, NSString * _Nullable))callback settingsAlertInVc:(nullable UIViewController *)vc{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *msg = nil;
            if (status == PHAuthorizationStatusRestricted) {
                msg = @"APP无法访问相册，请检测手机是否开启了家长控制";
                if (callback) callback(ZHAuthorityDeny, msg);
            }else if (status == PHAuthorizationStatusDenied){
                msg = @"APP无法访问相册，请到手机'设置'允许APP访问相册权限";
                if (callback) callback(ZHAuthorityDeny, msg);
            }else if(status == PHAuthorizationStatusNotDetermined){
                if (callback) callback(ZHAuthorityUnkonw, nil);
            }else{
                if (callback) callback(ZHAuthorityOK, nil);
            }
            if (vc && msg) {
                UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:(UIAlertControllerStyleAlert)];
                [alertCtl addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
                [alertCtl addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    [self openSysSettingsComplete:nil];
                }]];
                [vc presentViewController:alertCtl animated:YES completion:nil];
            }
        });
    }];
}

+ (void)openSysSettingsComplete:(void (^)(BOOL))complete{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            if (complete) complete(success);
        }];
    }
}

@end
